package com.oceansoft.mobile.biz.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhuya on 2017/6/6.
 */
@Controller
@RequestMapping("api/standard")
public class ApiStandardItemsController {
    /**
     * 从菜单页面跳转到选择事项和部门页面
     */
    @RequestMapping("gotoPage/{pageName}")
    public String getPage(@PathVariable("pageName") String pageName, HttpServletRequest request, Model model) {
        String standardid = request.getParameter("standardid");
        model.addAttribute("caseName", Constant.caseNameMap.get(standardid));
        model.addAttribute("standardid", standardid);
        String source = (String) request.getSession().getAttribute("source");
        if (!StringUtils.isEmpty(source)) {
            model.addAttribute("source", source);
        }
        return "weixin/standard/" + pageName;
    }

    /**
     * 获取事项对应的部门
     * @return result
     */
    @ResponseBody
    @RequestMapping(value = "getDept")
    public Result getDept(HttpServletRequest request) throws IllegalArgumentException, IOException {
        String name = URLDecoder.decode(request.getParameter("casename"), "UTF-8");
        String url = Constant.host5 + "api/police/BMByCasename?casename=" + name;
        JSONObject json = JSONObject.parseObject(HttpClientUtil.doGet(url));
        Result result = new Result(json);
        return result;
    }

    /**
     * 从事项和部门选择页跳转到须知页面
     */
    @ResponseBody
    @RequestMapping(value = "saveSession")
    public void saveSession(HttpServletRequest request, Model model) {
        String standardid = request.getParameter("standardid");
        request.getSession().setAttribute("standardid",standardid);
        request.getSession().setAttribute("refguid" + standardid, request.getParameter("refguid"));
        request.getSession().setAttribute("refid" + standardid, request.getParameter("refid"));
        request.getSession().setAttribute("orgid" + standardid, request.getParameter("orgid"));
    }

    /**
     * 获取事项对应的事项详情
     * http://172.16.1.101:8080/api/getcase/GetCaseInfo2?refID= &orgId=&casename=
     * @return result
     */
    @ResponseBody
    @RequestMapping(value = "standardItem")
    public Result standardItem(HttpServletRequest request)  {
        String standardid = request.getParameter("standardid");
        String refguid = (String) request.getSession().getAttribute("refguid" + standardid);
        String orgid = (String) request.getSession().getAttribute("orgid" + standardid);
        String casename = Constant.caseNameMap.get(standardid);
        String url = Constant.host5 + "api/getcase/GetCaseInfo2?refID=" + refguid + "&orgId=" + orgid + "&casename=" + casename;
        JSONObject json = null;
        try {
            json = JSONObject.parseObject(HttpClientUtil.doGet(url));
            String url1 = Constant.host5 + "api/getcase/GetCaseBasisList?caseRefId=" + refguid;//获取事项依据列表
            JSONObject json1 = JSONObject.parseObject(HttpClientUtil.doGet(url1));
            JSONArray j = JSONObject.parseArray(json1.get("data").toString());
            if (j.size() != 0) {
                String s = j.getJSONObject(0).get("BASISCONTENT").toString();
                json.put("xkyj", s);
            }

            String url2 = Constant.host5 + "api/getcase/GetCaseMaterial?refID=" + refguid;//事项材料列表
            JSONObject json2 = JSONObject.parseObject(HttpClientUtil.doGet(url2));
            JSONArray jj = JSONObject.parseArray(json2.get("data").toString());
            String sqcl = "";
            if (jj.size() > 0) {
                for (int i = 0; i < jj.size(); i++) {
                    String str = (i + 1) + "、" + jj.getJSONObject(i).get("MATERIAL").toString() + " <br/> ";
                    sqcl += str;
                }
            }
            json.put("sqcl", sqcl);
        }catch (IOException e){
            e.printStackTrace();
        }
        Result result = new Result(json);
        return result;
    }

    /**
     * 新增一个需要登录的跳转控制
     * @return
     */
    @RequestMapping(value = "gotopageWithUser/{pageName}")
    public String gotoMattersPageWithUser(@PathVariable("pageName") String pageName, HttpServletRequest request, Model model) {
        String standardid = request.getParameter("standardid");
        model.addAttribute("caseName", Constant.caseNameMap.get(standardid));
        model.addAttribute("standardid", standardid);
        boolean b = false;
        try{
            b = WeixinUtil.checkIsLoginUser(request);
            String source = (String) request.getSession().getAttribute("source");
            if (!StringUtils.isEmpty(source)) {
                model.addAttribute("source", source);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
//        b=true;
            if (!b) {
                model.addAttribute("openId", (String) request.getSession().getAttribute("openId"));
                model.addAttribute("gotoPage", "/api/standard/gotopageWithUser/" + pageName);
                return "weixin/login/login";
            } else {
                Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
                model.addAttribute("data", member);
                return "weixin/standard/" + pageName;
            }


    }

    /**
     * 从个人信息页面跳转到上传信息页面
     * http://172.16.1.101:8080/api/SXInfo/GetSXInfoBy?caseName= &orgGuid=
     */
    @RequestMapping(value = "gotoUpload", method = RequestMethod.GET)
    public String gotoUpload(HttpServletRequest request, Model model) {
        String standardid = (String)request.getSession().getAttribute("standardid");
        String orgid = (String) request.getSession().getAttribute("orgid"+ standardid);
        String casename = Constant.caseNameMap.get(standardid);

        Map<String, String> param = new HashMap<String, String>();
        param = (Map<String, String>) request.getSession().getAttribute("apply");
        String url = Constant.host5 + "api/SXInfo/GetSXInfoBy?caseName=" + casename + "&orgGuid=" + orgid;
        try {
            Result rr = JSONObject.parseObject(HttpClientUtil.doGet(url), Result.class);
            if(rr.getData()==null||rr.getData()==""){
                model.addAttribute("msg","暂无申请材料");
                return "weixin/standard/standard4";
            }
            JSONArray array = JSONArray.parseArray(rr.getData().toString());
            model.addAttribute("cl", rr);
            model.addAttribute("count", array.size());
        }catch (IOException e){
            e.printStackTrace();
        }
//        request.getSession().removeAttribute("items_fj");
        return "weixin/standard/standard4";
    }

    /**
     * 申请
     */
    @ResponseBody
    @RequestMapping(value = "applyPerson", method = RequestMethod.POST)
    public Result applyPerson(HttpServletRequest request) {
        String standardid = request.getParameter("standardid");
        Map<String, String> param = new HashMap<String, String>();
        param = RequestUtils.buildParamsByNamesFromRequest(request);
        param.put("refid", (String) request.getSession().getAttribute("refguid"+standardid));
        param.put("orgId", (String) request.getSession().getAttribute("orgid"+standardid));
        param.put("caseName", Constant.caseNameMap.get(standardid));
        param.put("declareCaseGuid", (String) request.getSession().getAttribute("refid"+standardid));
        request.getSession().setAttribute("apply", param);
        return new Result();
    }

    /**
     * 图片上传
     * @param type
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "uploadMsg", method = RequestMethod.POST)
    public Result uploadMsg(@RequestParam("type") String type, MultipartHttpServletRequest request) {
        String caseMatGuid = type;
        //type字段用于识别前台传过来的不同图片
        //type_1
        //Result result = uploadFJ(type, request, "pzctrl",type);
        Result result = RequestUtils.saveFj(request, "pzctrl", caseMatGuid, false);
        Map<String, Result> m = (Map<String, Result>) request.getSession().getAttribute("items_fj");
        request.getSession().removeAttribute("items_fj");
        if (null == m) {
            m = new HashMap<String, Result>();
        }
        m.put("items_fj" + type, result);
        request.getSession().setAttribute("items_fj", m);
        return result;
    }

    /**
     * 申报
     */
    @ResponseBody
    @RequestMapping(value = "standardItemAllSubmit", method = RequestMethod.POST)
    public Result standardItemAllSubmit(HttpServletRequest request, @RequestParam("declareCaseGuid") String declareCaseGuid) {
        Map<String, String> param = (Map<String, String>) request.getSession().getAttribute("apply");
        Result result = RequestUtils.submitShenbao(RequestUtils.map2Json(param), request, "", "items_fj", true);
        request.getSession().removeAttribute("apply");
        return result;
    }


}
